package com.iretailer.report.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iretailer.report.mapper.ActivityMapper;
import com.iretailer.report.model.Activity;
import com.iretailer.report.model.ActivityMall;
import com.iretailer.report.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther: xjw
 * @Date: 2019/1/24 09:40
 * @Description:
 */
@Service
public class ActivityService extends ServiceImpl<ActivityMapper, Activity> {
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ActivityMallService activityMallService;

    /**
     * 根据 id 删除
     * 如果 Activity 和 Mall 有关联则不能删除，如果没有关联则可以删除
     */
    public boolean delete(String id) {
        List<ActivityMall> findActivityMall = activityMallService.list(new QueryWrapper<ActivityMall>().lambda().eq(ActivityMall::getActivityId, id));
        if (findActivityMall.size() > 0) {
            return false;
        } else {
            activityMapper.deleteById(id);
            return true;
        }
    }

    /**
     * 新增或者更新
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean saveOrUpdate(Activity activities, List<String> mallIds) {

        if (StringUtil.notEmpty(activities.getId())) {
            activityMapper.updateById(activities);
        } else {
            activityMapper.insert(activities);
        }
        //保存 关联关系
        if (mallIds != null) {
            // 删除所有的关联关系
            activityMallService.remove(new QueryWrapper<ActivityMall>().lambda().eq(ActivityMall::getActivityId, activities.getId()));
            //保存新的关联关系
            List<ActivityMall> saveList = mallIds.stream().map(it -> new ActivityMall(activities.getId(), it)).collect(Collectors.toList());
            activityMallService.saveBatch(saveList);
        }
        return true;
    }

    /**
     * 根据关联的 MallId 和 开始时间与结束时间进行查询
     */
    public List<Activity> selectActivityByMallId_Time(String mallId, String startTime, String endTime) {
        return activityMapper.selectActivityByMallId_Time(mallId, startTime, endTime);
    }

    /**
     * 根据用户的 Id 查询相关的 Activity
     */
    public List<Activity> selectActivityByUserId(String userId) {
        return activityMapper.selectActivityByUserId(userId);
    }
}
